package Demo1_11;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-01-11
 * Time:21:50
 */
// 定义链表节点类
class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class MergeTwoSortedLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 创建一个虚拟头节点，方便操作
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        // 遍历两个链表，比较节点值大小，将较小的节点连接到新链表中
        while (list1!= null && list2!= null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        // 如果list1还有剩余节点，将其连接到新链表后面
        if (list1!= null) {
            cur.next = list1;
        }
        // 如果list2还有剩余节点，将其连接到新链表后面
        if (list2!= null) {
            cur.next = list2;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        // 可以在这里构建测试用的链表并调用mergeTwoLists方法进行测试
        ListNode list1 = new ListNode(1);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(5);
        list1.next = node2;
        node2.next = node3;

        ListNode list2 = new ListNode(2);
        ListNode node5 = new ListNode(4);
        ListNode node6 = new ListNode(6);
        list2.next = node5;
        node5.next = node6;

        MergeTwoSortedLists merger = new MergeTwoSortedLists();
        ListNode mergedList = merger.mergeTwoLists(list1, list2);

        // 输出合并后的链表，验证结果
        while (mergedList!= null) {
            System.out.print(mergedList.val + " ");
            mergedList = mergedList.next;
        }
    }
}